<?php
/**
 * ResetpassController
 * 
 * @author
 * @version 
 */
require_once 'Zend/Controller/Action.php';
class User_ResetpassController extends Zend_Controller_Action
{
    public function init() {	
		//set layout
    	$layoutPath = APPLICATION_PATH  . '/templates/default/default';
		$option = array (	'layout' 		=> 'index', 
              	        'layoutPath' 	=> $layoutPath );
		Zend_Layout::startMvc ( $option );
	}
	
    public function indexAction ()
    {
       	Zend_Loader::loadClass("UserModel");
        Zend_Loader::loadClass("MailModel");
    	Zend_Loader::loadClass("NewUserMailTemplate");
    	Zend_Loader::loadClass("PasswordResetMailTemplate");
    	Zend_Loader::loadClass("AuthModel");

    	$user = new UserModel();
       	$view = $this->view;
       	
        $request = $this->getRequest();
        $email = $request->getParam("recovery-mail");
        $view->email = $email;
        
       	//TODO get old user info
       	$user_info = $user->getUserInfoByEmail($email);
       	if (!$user_info){
       		$view->err_msg = "このメールアドレスはデータベースに存在していません。";
       		return;
       	}else{
	       	//TODO パスワードリセット
		    $account_info = $user->resetpass($email);
	    	
	        if($account_info){
	        	//TODO ユーザに新しいアカウントを送る
		    	$mail_model = new MailModel();
		    	$mail_model->setReceive_mail($account_info['email']);
		    	$mail_model->setReceive_name($account_info['name']);
				$template = new PasswordResetMailTemplate($account_info['username'], $account_info['new-pass']);
				
		    	$mail_model->setSubject($template->getSubject());
		    	$mail_model->setContent($template->getHtmlContent());
		    	$send_result = $mail_model->send();
		    	
		    	if(!$send_result){
		    		//TODO restore old password
		    		$data = array('password' => $user_info->password);
		    		$user->updateUserData($user_info->id, $data);

		    		//TODO show error messages
		    		$view->err_msg = "このメールに送信することができません。";
		    		return;		
		    	}
	        }
       	}
    }
}
